#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50
USE_PROCD=1

LOGFILE="npc.log"
tmp_conf_dir="/tmp/etc/"
tmp_conf_file="npc.conf"

tmp_conf_path="$tmp_conf_dir$tmp_conf_file"

export Enabled 
export server_addr server_port protocol vkey compress crypt log_level auto_reconnection

npc_header() {
	config_get Enabled $1 enabled
	config_get server_addr $1 server_addr
	config_get server_port $1 server_port
	config_get protocol $1 protocol
	config_get vkey $1 vkey
	config_get compress $1 compress
	config_get crypt $1 crypt
	config_get log_level $1 log_level
	config_get auto_reconnection $1 auto_reconnection
}

npc_write_bool() {
	val="$1"
	conffile="$2"

	if [ "${val}" = "0" ]; then
		echo "${val}=false" >> $conffile
	else
		echo "${val}=true" >> $conffile
	fi
}

npc_gen_conf() {
	if [ ! -d "$tmp_conf_dir" ]; then
		mkdir -p "$tmp_conf_dir"
	fi

	echo "[common]" >$tmp_conf_path
	echo "server_addr=${server_addr}:${server_port}" >> $tmp_conf_path
	echo "conn_type=${protocol}" >> $tmp_conf_path
	echo "vkey=${vkey}" >>$tmp_conf_path
	echo "auto_reconnection=${auto_reconnection}" >> $tmp_conf_path

	npc_write_bool compress $tmp_conf_path
	npc_write_bool crypt $tmp_conf_path
}

start_service() {
	config_load npc
	config_foreach npc_header npc

	if [ "$Enabled" = "1" ];then
		npc_gen_conf npc
		logger -t FRPC 'Starting Nps Client service' 
		#service_start /usr/bin/npc -config=$tmp_conf_path -log_level=$Log_level -log_path=$LOGFILE
		procd_open_instance
		procd_set_param command /usr/bin/npc -config=$tmp_conf_path -log_level=$log_level
		procd_set_param file $tmp_conf_path
		procd_set_param respawn
		procd_set_param stdout 1
		procd_set_param stderr 1
		procd_close_instance
	fi
}

service_triggers()
{
        procd_add_reload_trigger "npc"
}

reload_service()
{
        echo "restarting npc service"
        stop
        start
}

